package com.fatmeraid.custom.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Configuration
public class JacksonConfig {

	// 自定义 LocalDateTime 格式化器（统一序列化和反序列化格式）
	private static final DateTimeFormatter LOCAL_DATE_TIME_FORMATTER =
			DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

	@Bean
	public ObjectMapper objectMapper() {
		ObjectMapper mapper = new ObjectMapper();

		// 1. 处理 Long 类型序列化为字符串（解决 userId 精度问题）
		SimpleModule longModule = new SimpleModule();
		longModule.addSerializer(Long.class, ToStringSerializer.instance);
		longModule.addSerializer(long.class, ToStringSerializer.instance);
		mapper.registerModule(longModule);

		// 2. 处理 Java 8 日期类型（LocalDateTime）的序列化和反序列化
		JavaTimeModule javaTimeModule = new JavaTimeModule();

		// 序列化器：将 LocalDateTime 转为指定格式的字符串
		javaTimeModule.addSerializer(
				LocalDateTime.class,
				new LocalDateTimeSerializer(LOCAL_DATE_TIME_FORMATTER)
		);

		// 反序列化器：将字符串转为 LocalDateTime（解决解析错误的关键）
		javaTimeModule.addDeserializer(
				LocalDateTime.class,
				new LocalDateTimeDeserializer(LOCAL_DATE_TIME_FORMATTER)
		);

		// 如需支持其他日期类型，可添加对应的序列化器和反序列化器
		// javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
		// javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

		mapper.registerModule(javaTimeModule);

		// 3. 其他配置
		mapper.disable(com.fasterxml.jackson.databind.MapperFeature.REQUIRE_HANDLERS_FOR_JAVA8_TIMES);

		return mapper;
	}
}